#import "UIView+Gradient.h"
#import <QuartzCore/QuartzCore.h>
#import <objc/runtime.h> // 添加这行！

@interface UIView ()
@property (nonatomic, assign) BOOL isObservingBounds; // 标记是否已注册 KVO 观察者
@end

@implementation UIView (Gradient)

- (void)setIsObservingBounds:(BOOL)isObservingBounds {
    objc_setAssociatedObject(self, @selector(isObservingBounds),
                             @(isObservingBounds), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isObservingBounds {
    NSNumber *value = objc_getAssociatedObject(self, @selector(isObservingBounds));
    return value ? value.boolValue : NO;
}

- (CAGradientLayer *)addVerticalGradientWithTopColor:(UIColor *)topColor
                                          bottomColor:(UIColor *)bottomColor {
    return [self addGradientWithStartColor:topColor
                                  endColor:bottomColor
                                startPoint:CGPointMake(0.5, 0.0)
                                  endPoint:CGPointMake(0.5, 1.0)];
}

- (CAGradientLayer *)addGradientWithStartColor:(UIColor *)startColor
                                       endColor:(UIColor *)endColor
                                     startPoint:(CGPoint)startPoint
                                       endPoint:(CGPoint)endPoint {
    // 先移除已有的渐变图层
    [self removeGradientLayer];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.bounds;
    gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    gradientLayer.name = @"gradientLayer";
    
    [self.layer insertSublayer:gradientLayer atIndex:0];
    
    // 只有当未注册观察者时才添加 KVO
    if (!self.isObservingBounds) {
        [self addObserver:self forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew context:nil];
        self.isObservingBounds = YES;
    }
    
    return gradientLayer;
}

- (void)removeGradientLayer {
    // 移除渐变图层
    for (CALayer *layer in self.layer.sublayers) {
        if ([layer.name isEqualToString:@"gradientLayer"]) {
            [layer removeFromSuperlayer];
            break;
        }
    }
    
    // 只有当已注册观察者时才移除 KVO
    if (self.isObservingBounds) {
        @try {
            [self removeObserver:self forKeyPath:@"bounds"];
        } @catch (NSException *exception) {
            // 忽略异常，防止因未注册而崩溃
        }
        self.isObservingBounds = NO;
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"bounds"]) {
        for (CALayer *layer in self.layer.sublayers) {
            if ([layer.name isEqualToString:@"gradientLayer"]) {
                layer.frame = self.bounds;
                break;
            }
        }
    }
}

//- (void)dealloc {
//    [self removeGradientLayer];
//}
+ (UIView *)createGradientViewWithFrame:(CGRect)frame
                               topColor:(UIColor *)topColor
                            topAlpha:(CGFloat)topAlpha
                          bottomColor:(UIColor *)bottomColor
                         bottomAlpha:(CGFloat)bottomAlpha {
    UIView *gradientView = [[UIView alloc] initWithFrame:frame];
    
    // 创建带透明度的颜色
    UIColor *topColorWithAlpha = [topColor colorWithAlphaComponent:topAlpha];
    UIColor *bottomColorWithAlpha = [bottomColor colorWithAlphaComponent:bottomAlpha];
    
    // 创建渐变色图层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = gradientView.bounds;
    gradientLayer.colors = @[(id)topColorWithAlpha.CGColor, (id)bottomColorWithAlpha.CGColor];
    gradientLayer.startPoint = CGPointMake(0.5, 0.0);  // 顶部中心
    gradientLayer.endPoint = CGPointMake(0.5, 1.0);    // 底部中心
    
    [gradientView.layer insertSublayer:gradientLayer atIndex:0];
    return gradientView;
}
@end
